package com.flash.es.service;

import com.alibaba.fastjson.JSON;
import com.flash.es.domain.Search;
import com.ruoyi.common.core.utils.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @description: TODO
* @author admin
* @date 2023/1/99:38
* @version 1.0
*/
@Service
public class SearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    public  List<Search> getes(Map map) throws IOException {
        String key = (String) map.get("key");
        SearchRequest searchRequest = new SearchRequest("variety_cs");//POST guli_product/_search
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        if(!StringUtils.isEmpty(key)){
            searchSourceBuilder.query(QueryBuilders.matchQuery("cuisinename", key));
        }
        HighlightBuilder cuisnename = new HighlightBuilder()
                .preTags("<strong style='color:red'>")
                .postTags("</strong>")
                .field("cuisinename");
        searchSourceBuilder.highlighter(cuisnename);
        searchRequest.source(searchSourceBuilder);//{   }
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);//点击发送
        SearchHits hits = searchResponse.getHits();
        SearchHit[] hits1 = hits.getHits();
        List<Search> list = Arrays.stream(hits1).map(documentFields -> {
            String sourceAsString = documentFields.getSourceAsString();
            Search search = JSON.parseObject(sourceAsString, Search.class);
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField highlightField = highlightFields.get("cuisinename");
            if (highlightField != null) {
                Text[] fragments = highlightField.getFragments();
                if (fragments.length > 0) {
                    search.setCuisinename(fragments[0].toString());
                }
            }
            return search;
        }).collect(Collectors.toList());
        return list;
    }
}
